<script setup>
import { onMounted, ref, watch } from 'vue'
import { deleteArticleApi, getArticleApi, getChannelApi } from '../../api'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import useUserStore from '../../store/userStore'
import { useRouter } from 'vue-router'

// 表单数据
const form = ref({
  page: 1,
  size: 3,
  status: '',
  channel_id: '',
  st: '',
  et: '',
})
// 频道列表
const channelList = ref([])

// 时间范围
const rangeDate = ref([])

// 文章列表
const articleList = ref([])

// 总数
const total = ref(0)

// 总页数
const totalPage = ref(0)

const router = useRouter()

// 监听时间范围改变
watch(rangeDate, (newVal) => {
  // 时间范围改变时清空时间
  if (!newVal || newVal.length === 0) {
    form.value.st = ''
    form.value.et = ''
    return
  }
  // 时间格式转换
  form.value.st = dayjs(newVal[0]).format('YYYY-MM-DD 00:00:00')
  form.value.et = dayjs(newVal[1]).format('YYYY-MM-DD 23:59:59')
})

// 获取文章列表
const onSubmit = async () => {
  const res = await getArticleApi(form.value)
  articleList.value = res.data.rows
  total.value = res.data.total
  totalPage.value = res.data.totalPage
}

// 每页数量改变
const handleSizeChange = (val) => {
  form.value.size = val
  onSubmit()
}

// 当前页码改变
const handleCurrentChange = (val) => {
  form.value.page = val
  onSubmit()
}
// 编辑文章
const onEdit = (id) => {
  router.push({
    path: '/post-article',
    query: { id },
  })
}

// 删除文章
const onDelete = async (id) => {
  console.log(id, '删除文章')

  const res = await deleteArticleApi(id)
  if (res.message === 'success') {
    ElMessage.success('删除成功')
    onSubmit()
  } else {
    ElMessage.error('删除失败')
  }
}

onMounted(async () => {
  // 获取频道列表
  const res = await getChannelApi()
  channelList.value = res.data
  // 获取文章列表
  onSubmit()
})
</script>

<template>
  <div>
    <div class="card">
      <!-- 表单 -->
      <el-form
        :model="form"
        label-width="auto"
      >
        <!-- 状态 -->
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio value="">全部</el-radio>
            <el-radio value="草稿">草稿</el-radio>
            <el-radio value="待审核">待审核</el-radio>
            <el-radio value="审核通过">审核通过</el-radio>
            <el-radio value="审核失败">审核失败</el-radio>
            <el-radio value="已删除">已删除</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 频道 -->
        <el-form-item
          label="频道"
          style="width: 400px"
        >
          <el-select
            v-model="form.channel_id"
            clearable
            placeholder="请选择频道"
          >
            <el-option
              v-for="item in channelList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
              >{{ item.name }}
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 日期 -->
        <el-form-item
          label="日期"
          style="width: 400px"
        >
          <el-date-picker
            v-model="rangeDate"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>

        <el-form-item label=" ">
          <el-button
            type="primary"
            @click="onSubmit"
          >
            筛选
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="card">
      <div class="table-title">根据筛选条件查询到 {{ total }} 条数据：</div>
      <!-- 表格 -->
      <el-table
        :data="articleList"
        border
        style="width: 100%"
        stripe
      >
        <el-table-column
          type="index"
          label="序号"
          width="60"
        />
        <el-table-column
          label="封面"
          width="90"
        >
          <template #default="{ row }">
            <el-image
              :src="row.cover_images[0]"
              style="width: 60px; height: 60px"
              fit="fill"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="title"
          label="标题"
        />
        <el-table-column
          prop="status"
          label="状态"
        />
        <el-table-column label="发布时间">
          <template #default="{ row }">
            {{ dayjs(row.pub_date).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column
          prop="channel_name"
          label="频道列表"
        />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button
              type="primary"
              :disabled="row.status === '已删除'"
              @click="onEdit(row.id)"
            >
              编辑
            </el-button>
            <el-popconfirm
              title="确定要删除吗？"
              @confirm="onDelete(row.id + '')"
            >
              <template #reference>
                <el-button
                  type="danger"
                  :disabled="
                    row.status === '已删除' ||
                    row.author_id !== useUserStore().userInfo.id
                  "
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="form.page"
          v-model:page-size="form.size"
          :page-sizes="[1, 3, 5, 10]"
          background
          layout="sizes, prev, pager, next,jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.card {
  border-radius: 10px;
  background-color: #fff;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.05);
}

.table-title {
  font-size: 13px;
  font-weight: 700;
  line-height: 40px;
  margin-bottom: 15px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}
</style>
